<template>
  <div class="add-subject">
    <el-form :model="formData" label-width="120px">
      <!-- 题目类型 -->
      <el-form-item label="题目类型">
        <el-select v-model="formData.type">
          <el-option label="单选题" :value="1" />
          <el-option label="多选题" :value="2" />
          <el-option label="判断题" :value="3" />
          <el-option label="简答题" :value="4" />
        </el-select>
      </el-form-item>

      <!-- 题目标题 -->
      <el-form-item label="题目标题">
        <el-input v-model="formData.detail" type="textarea" rows="3" />
      </el-form-item>

      <!-- 题目选项，仅在单选、多选、判断题时显示 -->
      <template v-if="[1, 2, 3].includes(formData.type)">
        <el-form-item label="题目选项">
          <div v-for="(option, index) in formData.subjectOptionList" :key="index" class="option-item">
            <!-- 单选多选题显示完整选项 -->
            <template v-if="[1, 2].includes(formData.type)">
              <el-input v-model="option.optionTitle" style="width: 80px" placeholder="选项标题" maxlength="1"
                :value="getOptionLabel(index)" disabled />
              <el-input v-model="option.optionContent" style="width: 300px" placeholder="选项内容" />
              <el-checkbox v-model="option.isRight" label="正确答案"
                @change="(val:any) => validateCorrectAnswers(val, index)" />
              <el-button type="danger" @click="removeOption(index)">删除</el-button>
            </template>
            <!-- 判断题只需要正确与否 -->
            <template v-else-if="formData.type === 3">
              <el-radio-group v-model="option.isRight">
                <el-radio :label="1">正确</el-radio>
                <el-radio :label="0">错误</el-radio>
              </el-radio-group>
            </template>
          </div>
          <el-button v-if="[1, 2].includes(formData.type)" @click="addOption">添加选项</el-button>
        </el-form-item>
      </template>

      <!-- 难度 -->
      <el-form-item label="题目难度">
        <el-select v-model="formData.difficult">
          <el-option label="简单" :value="1" />
          <el-option label="中等" :value="2" />
          <el-option label="困难" :value="3" />
        </el-select>
      </el-form-item>

      <!-- 分数 -->
      <el-form-item label="题目分数">
        <el-select v-model="formData.score">
          <el-option label="2分" :value="2" />
          <el-option label="4分" :value="4" />
          <el-option label="6分" :value="6" />
        </el-select>
      </el-form-item>

      <!-- 解析 -->
      <el-form-item label="题目解析">
        <el-input v-model="formData.parse" type="textarea" rows="3" />
      </el-form-item>

      <!-- 分类 -->
      <el-form-item label="题目分类">
        <el-select v-model="formData.categoryIdList" multiple :loading="categoryLoading" @change="handleCategoryChange">
          <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />

          <el-option v-if="!categoryLoading && hasMoreCategories" value="-1" label="加载更多..." @click="fetchCategories" />

          <el-option v-if="categoryLoading" disabled value="-1" label="加载中..." />
          <el-option v-if="!hasMoreCategories && categoryOptions.length > 0" disabled value="-1" label="没有更多数据" />
        </el-select>
      </el-form-item>

      <!-- 标签 -->
      <el-form-item label="题目标签">
        <el-select v-model="formData.labelIdList" multiple>
          <el-option v-for="item in labelList" :key="item.id" :label="item.labelName" :value="item.id" />
        </el-select>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">
          {{ submitLoading ? '提交中...' : '提交' }}
        </el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useBgwStores } from '@/stores/bgwStores'
import { storeToRefs } from 'pinia';
import type { BgwCategory } from '@/typedefined/Category';

const bgwStores = useBgwStores();

// 获取分类列表
const { getCategoryList, request2AddSubject,getLableList } = bgwStores;

// 分类列表，标签列表
const { categoryPageList,labelList } = storeToRefs(bgwStores);

// 表单数据
const formData = reactive({
  type: 1, // 题目类型
  detail: '', // 题目标题
  parse: '', // 题目解析
  difficult: 1, // 题目难度
  score: 2, // 题目分数
  subjectOptionList: [{ optionTitle: 'A', optionContent: '', isRight: 0 }],
  subjectCategoryList: [],
  subjectLabelList: [],
  labelIdList:[], // 标签id列表
  categoryIdList:[] // 分类id列表
})

// 修改分类相关的数据结构
const categoryOptions = ref<any>([]) // 分类选项列表
const categoryMap = ref<any>({}) // 添加映射关系存储
const categoryPage = ref(1)
const categoryLoading = ref(false)
const hasMoreCategories = ref(true)
const pageSize = 5

// 获取分类数据
const fetchCategories = async () => {
  if (categoryLoading.value || !hasMoreCategories.value) return

  try {
    categoryLoading.value = true;
    // 获取分类列表
    await getCategoryList(categoryPage.value, pageSize);
    const options: Array<any> = [];
    // 构建分类映射关系
    categoryPageList.value?.records.forEach((category: BgwCategory) => {

      // 添加一级分类
      options.push({
        id: category.id,
        label: category.categoryName,
        isParent: true // 标记为一级分类
      })

      // 处理二级分类
      if (category.towLevelCategoryList && category.towLevelCategoryList.length > 0) {
        category.towLevelCategoryList.forEach(subCategory => {
          options.push({
            value: subCategory.id,
            label: `${category.categoryName} - ${subCategory.categoryName}`,
            parentId: category.id // 记录父分类ID
          })
          // 存储二级分类与一级分类的关系
          categoryMap.value[subCategory.id] = category.id;
        })
      }
    })

    categoryOptions.value = [...categoryOptions.value, ...options]

    if (categoryPageList.value?.total && categoryPage.value * pageSize >= categoryPageList.value?.total) {
      hasMoreCategories.value = false
    } else {
      categoryPage.value++
    }
  } catch (error) {
    console.error('获取分类数据失败：', error)
  } finally {
    categoryLoading.value = false
  }
}

// 监听分类选择变化
const handleCategoryChange = (values: any) => {
  // 过滤掉"加载更多"选项的值 -1
  values = values.filter((value: any) => value !== -1)

  const newValues = new Set(values)

  // 检查是否选择了二级分类，自动添加对应的一级分类
  values.forEach((value: any) => {
    const parentId = categoryMap.value[value]
    if (parentId) {
      newValues.add(parentId)
    }
  })

  formData.subjectCategoryList = Array.from(newValues) as any;
}

// 获取标签数据
const fetchLabels = async () => {
  try {
    await getLableList();
  } catch (error) {
    console.error('获取标签数据失败：', error)
  }
}

// 组件加载时获取分类和标签数据
onMounted(() => {
  fetchCategories()
  fetchLabels()
})

// 添加获取选项标签的方法
const getOptionLabel = (index: number) => {
  return String.fromCharCode(65 + index) // 65 是字母 'A' 的 ASCII 码
}

// 修改添加选项的方法
const addOption = () => {
  if (formData.subjectOptionList.length >= 26) { // 限制最多26个选项（A-Z）
    ElMessage.warning('最多只能添加26个选项')
    return
  }
  formData.subjectOptionList.push({
    optionTitle: String.fromCharCode(65 + formData.subjectOptionList.length), // 自动设置下一个字母
    optionContent: '',
    isRight: 0
  })
}

// 删除选项
const removeOption = (index: number) => {
  formData.subjectOptionList.splice(index, 1)
}

// 添加 loading 状态
const submitLoading = ref(false)

// 验证正确答案数量
const validateCorrectAnswers = (val: any, currentIndex: number) => {
  // 单选题：只能有一个正确答案
  if (formData.type === 1) {
    formData.subjectOptionList.forEach((option: any, index: number) => {
      if (index !== currentIndex) {
        option.isRight = false
      }
    })
  }

  // 多选题：如果取消选中导致正确答案少于2个，显示警告
  if (formData.type === 2 && !val) {
    const rightAnswersCount = formData.subjectOptionList.filter(option => option.isRight).length
    if (rightAnswersCount < 2) {
      ElMessage.warning('多选题至少需要2个正确答案')
    }
  }
}

// 修改提交表单验证
const submitForm = async () => {
  if (submitLoading.value) return

  try {
    submitLoading.value = true

    // 表单验证
    if (!formData.detail) {
      ElMessage.warning('请输入题目标题')
      return
    }
    if (!formData.parse) {
      ElMessage.warning('请输入题目解析')
      return
    }

    // 选项验证
    if ([1, 2].includes(formData.type)) {
      // 检查选项数量
      if (formData.subjectOptionList.length < 2) {
        ElMessage.warning('请至少添加两个选项')
        return
      }
      // 检查选项是否填写完整
      const hasEmptyOption = formData.subjectOptionList.some(
        option => !option.optionTitle || !option.optionContent
      )
      if (hasEmptyOption) {
        ElMessage.warning('请完整填写所有选项')
        return
      }

      // 检查正确答案数量
      const rightAnswersCount = formData.subjectOptionList.filter(option => option.isRight).length

      if (formData.type === 1 && rightAnswersCount !== 1) {
        ElMessage.warning('单选题必须有且仅有一个正确答案')
        return
      }

      if (formData.type === 2 && rightAnswersCount < 2) {
        ElMessage.warning('多选题至少需要2个正确答案')
        return
      }
    }

    // 判断题只需要验证是否选择了答案
    if (formData.type === 3 && !formData.subjectOptionList[0].isRight) {
      ElMessage.warning('请选择正确答案')
      return
    }

    // 在发送请求前转换 isRight 的值
    const submitData = { ...formData }
    submitData.subjectOptionList = formData.subjectOptionList.map(option => ({
      ...option,
      isRight: typeof option.isRight === 'boolean' ? (option.isRight ? 1 : 0) : option.isRight
    }))

    // 发送请求
    await request2AddSubject(submitData as any);
    ElMessage.success('添加题目成功')
    resetForm()
  } catch (error:any) {
    console.error('添加题目失败：', error)
    ElMessage.error('添加题目失败：' + (error.message || '未知错误'))
  } finally {
    submitLoading.value = false
  }
}

// 修改重置表单方法
const resetForm = () => {
  Object.assign(formData, {
    type: 1,
    detail: '',
    parse: '',
    difficult: 1,
    score: 2,
    subjectOptionList: [{ optionTitle: 'A', optionContent: '', isRight: 0 }], // 初始选项为 A
    categoryIdList: [],
    labelIdList: []
  })
}


</script>

<style scoped>
.add-subject {
  padding: 20px;
}

.option-item {
  margin-bottom: 10px;
  display: flex;
  gap: 10px;
  align-items: center;
}
</style>